package client

import (
	"context"
	"google.golang.org/grpc"
	hotel "hotel_3.27/common/proto"
)

type Handler func(ctx context.Context, in hotel.HotelClient) (interface{}, error)

func HotelClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := hotel.NewHotelClient(dial)

	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}

	defer dial.Close()
	return res, nil
}

func SendSms(ctx context.Context, i *hotel.SendSmsReq) (*hotel.SendSmsResp, error) {
	client, err := HotelClient(ctx, func(ctx context.Context, in hotel.HotelClient) (interface{}, error) {
		sms, err := in.SendSms(ctx, i)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*hotel.SendSmsResp), nil
}

func Login(ctx context.Context, i *hotel.LoginReq) (*hotel.LoginResp, error) {
	client, err := HotelClient(ctx, func(ctx context.Context, in hotel.HotelClient) (interface{}, error) {
		login, err := in.Login(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*hotel.LoginResp), nil
}
func OrderAdd(ctx context.Context, i *hotel.OrderAddReq) (*hotel.OrderAddResp, error) {
	client, err := HotelClient(ctx, func(ctx context.Context, in hotel.HotelClient) (interface{}, error) {
		login, err := in.OrderAdd(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*hotel.OrderAddResp), nil
}
func OrderList(ctx context.Context, i *hotel.OrderListReq) (*hotel.OrderListResp, error) {
	client, err := HotelClient(ctx, func(ctx context.Context, in hotel.HotelClient) (interface{}, error) {
		login, err := in.OrderList(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*hotel.OrderListResp), nil
}
